﻿var ProductListViewModel = function () {
    var self = this;

    //Public data properties
    self.filter = {
    };

    self.sources = {
    };
    
    self.selectedListStyle = ko.observable('grid');

    self.showPreviewImage = function (data, event) {

        // these 2 variable determine popup's distance from the cursor
        // you might want to adjust to get the right result
        var xOffset = 10;
        var yOffset = 30;

        event.currentTarget.t = event.currentTarget.title;
        event.currentTarget.title = "";
        $("body").append("<div id='preview'><img src='" + event.currentTarget.href + "' alt='" + data.Name() + "' /><div class='previewtext'><h4>" + data.Name() + "</h4></div></div>");
        $("#preview")
            .css("position", "absolute")
            .css("top", (event.pageY - xOffset) + "px")
            .css("left", (event.pageX + yOffset) + "px")
            .fadeIn("fast");

        $(event.currentTarget).mousemove(function (e) {

            $("#preview")
                .css("top", (e.pageY - xOffset) + "px")
                .css("left", (e.pageX + yOffset) + "px");
        });
        
    };

    self.hidePreviewImage = function(data, event) {

        event.currentTarget.title = event.currentTarget.t;
        $("#preview").remove();

    };

    self.hideProductElement = function (element, index, data) {

        var fastRemove = false;
        if (self.filter.MyBoard() && !data.IsBoardElement()) {

            if (element.nodeType === 1) {

                $(element).fadeOut(500, function() {
                    $(element).remove();
                });

            } else {
                fastRemove = true;
            }

        } else {
            fastRemove = true;
        }

        if (fastRemove) {
            ko.removeNode(element);
        }

    };

    self.changeListStyle = function (style) {

        $.cookie('selectedListStyle', style, { expires: 365, path: '/' });

        if (self.searchResult.products().length > 100) {

            self.searchResult.products([]);
            self.filterChanged(0);

        }

        self.selectedListStyle(style);

    };

    self.toggleMyBoard = function() {

        var myBoard = self.filter.MyBoard();

        self.searchResult.products([]);

        self.filterReset();
        self.filter.MyBoard(!myBoard);
        self.filterChanged(10);

    };

    self.toggleProductInBoard = function(data) {

        var url;
        if (!data.IsBoardElement()) {
            url = app.relativeUrl + '/user/ajax.asp?act=favorite'; 
        } else {
            url = app.relativeUrl + '/user/ajax.asp?act=delfavorite';
        }
		
		
	var data2;
	data2="id="+data.Uid();
	$.ajax({
	type:"post",
	cache:false,
	url:url,
	data:data2,
	error:function(){alert("fail");},
	success:function(_)
	{
		var act=_.substring(0,1);
		var info=_.substring(1);
		switch(act)
		{
			case "0":
				$.fn.tips({type:"error",content:info,time:3000});
				break;
			case "1":
				 data.IsBoardElement(!data.IsBoardElement());

                    if (self.filter.MyBoard()) {
                        self.searchResult.products.remove(data);

                    }
				break;
			case "2":
				$.fn.tips({type:"ok",content:info,time:3000});
				break;
			default:
				alert(_);
				break;
		}
	}});
		
    };

    self.shareBoard = function() {

        var url = app.relativeUrl + '/product/shareboard' +
                    '?_=' + new Date().getTime();
        $('#share-board-modal').modal({
            remote: url
        });
        $('#share-board-modal .modal-content').html('');
        $('#share-board-modal').off('hidden.bs.modal').on('hidden.bs.modal', function () {
            $(this).removeData('bs.modal');
        });

    };

    self.isProductsLoading = ko.observable(false);

    self.searchResult = {

        numberOfProducts: ko.observable(0),
        numberOfDownloads: ko.observable(0),
        numberOfManufacturers: ko.observable(0),
        products: ko.observableArray([])

    };

    self.searchErrors = ko.observableArray([]);

    self.dotdotdot = function(string, maxLenght) {

        var truncated = string;

        if (string && string.length > maxLenght) {

            //cut off by word, finding the last space
            var lastIndex = string.lastIndexOf(' ', maxLenght);

            truncated = $.trim(string).substring(0, lastIndex != -1 ? lastIndex : maxLenght) + '…';
        }

        return truncated;
    };

    self.serialize = function(obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p) && obj[p] && obj[p] != '') {
                str.push(encodeURIComponent(p.toLowerCase()) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    };

    self.isFilterActive = ko.observable(false);

    self.filterChanged = function(timeOut) {

        if (!timeOut) timeOut = 500;

        delay(function() {
            var data = ko.mapping.toJS(self.filter);
            var params = self.serialize(data);

            self.isFilterActive(params != '');

           // if (typeof History != 'undefined' && History.enabled) { //html5 compatible browsers, using history api

              //  History.replaceState(ko.mapping.toJS(self.filter), document.title, (params != '' ? ('?' + params) : (app.relativeUrl + '/product')));

           // } else { //in case of old browsers, reloading the page

           //     window.location = app.relativeUrl + '/product' + (params != '' ? ('?' + params) : '');
             //   return;

           // }

            if (refreshProductsXhr != null) {
                refreshProductsXhr.abort();
                refreshProductsXhr = null;
            }
            self.actualskip = 0;
            self.hasNextPage(true);
            self.searchResult.products([]);
            self.refreshProducts(self.actualskip);

        }, timeOut);

    };

    self.filterReset = function() {

        self.filter.FreeText(null);
        self.filter.Manufacturer(null);
        self.filter.CategoryId(null);
        self.filter.MaterialId(null);
        self.filter.BuildingTypeId(null);
        self.filter.FunctionalSpaceId(null);
        self.filter.FileTypeId(null);
        self.filter.ContentTypeId(null);
        self.filter.MyBoard(false);
        self.filter.Board(null);

    };

    //Init
    self.init = function () {

        //restore selected list style
        var selectedListStyle = $.cookie('selectedListStyle');
        if (selectedListStyle) {
            self.selectedListStyle(selectedListStyle);
        }

        //set filter active flag
        var data = ko.mapping.toJS(self.filter);
        var params = self.serialize(data);
        self.isFilterActive(params != '');

    };

    self.setWaypoint = function() {

        $.waypoints('destroy');
        $('#pager_container').waypoint(function(direction) {

            if (direction === 'down' || direction === 'right') {
                self.viewNextObjects();
            }

        }, {
            offset: 'bottom-in-view',
            triggerOnce: true
        });

    };

    //Refresh
    self.hasNextPage = ko.observable(true);
    self.actualskip = 0;
    var refreshProductsXhr = null;
    self.refreshProducts = function(skip) {

        self.isProductsLoading(true);

        var data = ko.mapping.toJS(self.filter);
        data.skip = skip;

        //clear errors
        self.searchErrors([]);
         app.relativeUrl=''
        refreshProductsXhr = $.ajax({
            url: app.relativeUrl + '../../ajax/product.asp',
            cache: false,
            type: 'GET',
            dataType: 'json',
            contentType: "application/json",
            data: data,
            success: function(json) {
                if (json.IsValid) {
                    var responseData = json.Data;

                    if (!responseData.HasMoreElement) {
                        self.hasNextPage(false);
                    }

                    self.searchResult.numberOfProducts(responseData.NumberOfProducts);
                    self.searchResult.numberOfDownloads(responseData.NumberOfDownloads);
                    self.searchResult.numberOfManufacturers(responseData.NumberOfManufacturers);

                    //add to array
                    //self.searchResult.products.push.apply(self.searchResult.products, json.Products);
                    self.searchResult.products.push.apply(self.searchResult.products, ko.mapping.fromJS(responseData.Products)());

                } else {
				

                    //show errors
                    self.searchErrors.push.apply(self.searchErrors, getAllMessageAsArrayOfString(json.Errors));

                }
            },
            complete: function() {
            
                self.isProductsLoading(false);
                refreshProductsXhr = null;

            }
        });

    };

    self.viewNextObjects = function() {

        self.actualskip = self.searchResult.products().length;
        self.refreshProducts(self.actualskip);

    };

}